#include "MacCommon.h"
#include "Window.h"
#include "CoreFoundation/CoreFoundation.h"
#include "AppKit/AppKit.h"

using namespace Hiranipra;
using namespace Hiranipra::Platform;

Window::Window( const WindowParameters& params )
{
	NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect( 0, 0, params.DefaultSize.w, params.DefaultSize.h ) styleMask:NSBorderlessWindowMask backing:NSBackingStoreRetained defer:FALSE];
	_handle = window;
	
	string title = NarrowString( params.DefaultTitle );
	NSString* titleString = [NSString stringWithUTF8String:title.c_str()];
	[window setTitle:titleString];
	[titleString release];
	
	this->Retain();
	_isClosed = false;
}

Window::~Window()
{
	if( _isClosed == false )
		this->Close();
}

void Window::SetTitle( const wstring& newTitle )
{
	if( _isClosed == true )
		return;
	NSWindow* window = ( NSWindow* )_handle;
	
	string title = NarrowString( newTitle );
	NSString* titleString = [NSString stringWithUTF8String:title.c_str()];
	[window setTitle:titleString];
	[titleString release];
}

uint32 Window::GetCurrentDisplay() const
{
	if( _isClosed == true )
		return 0;
	// TODO: GetCurrentDisplay
	return 0;
}

void Window::MoveToDisplay( const uint32 displayId )
{
	if( _isClosed == true )
		return;
	// TODO: MoveToDisplay
}

Point2D Window::GetLocation() const
{
	if( _isClosed == true )
		return Point2D( 0, 0 );
	NSWindow* window = ( NSWindow* )_handle;
	return Point2D( 0, 0 );
}

void Window::SetLocation( const Point2D& location )
{
	if( _isClosed == true )
		return;
	NSWindow* window = ( NSWindow* )_handle;
}

Size2D Window::GetSize() const
{
	if( _isClosed == true )
		return Size2D( 1, 1 );
	NSWindow* window = ( NSWindow* )_handle;
	return Size2D( 1, 1 );
}

void Window::SetSize( const Size2D& size )
{
	if( _isClosed == true )
		return;
	NSWindow* window = ( NSWindow* )_handle;
}

WindowState Window::GetState() const
{
	if( _isClosed == true )
		return Normal;
	// TODO: GetState
	return Normal;
}

void Window::SetState( const WindowState state )
{
	if( _isClosed == true )
		return;
	// TODO: SetState
}

bool Window::IsMinimized() const
{
	if( _isClosed == true )
		return false;
	// TODO: IsMinimized
	return false;
}

void Window::Close()
{
	if( _isClosed == true )
		return;
	_isClosed = true;
	NSWindow* window = ( NSWindow* )_handle;
	[window close];
	[window release];
	_handle = NULL;
	this->EventSource.Fire( WindowEvent( this, WindowEvent::Closed ) );
}
